package cn.com.gzheroli.bfw.service.impl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.binary.Base64;
import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.gzheroli.bfw.mapper.ActUserMapper;
import cn.com.gzheroli.bfw.pojo.base.TSBaseUser;
import cn.com.gzheroli.bfw.pojo.base.TSType;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.core.common.mapper.CommonMapper;
import cn.com.gzheroli.core.common.mapper.UserMapper;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.HeroService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.util.PasswordUtil;
import cn.com.gzheroli.core.util.mybatis.SqlMapper;
import cn.com.gzheroli.service.bfw.UserService;
import cn.com.gzheroli.tag.vo.easyui.ZNodes;


@Service("userService")
public class UserServiceImpl  implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CommonMapper commonMapper;
	@Autowired
	private ActUserMapper actUserMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private HeroService heroService;
		
	private static final Logger logger = Logger
			.getLogger(UserServiceImpl.class);
	@Autowired
	private SystemService systemService;
	@Autowired
	SqlMapper sqlMapper;
	/*private Session getSession(){
		return systemService.getSession();
	}*/
	public TSUser checkUserExits(TSUser user) {
		if(user.getUserName()==null||user.getPassword()==null||user.getUserName().trim().equals(""))
			return null;
		String userName=user.getUserName();
		String oldpassword=user.getPassword();
		// List<TSUser> usersList =jdbcDao.getBeanforList("select * from T_S_BASE_USER bu,T_S_USER u where bu.ID=u.ID ",TSUser.class,new Object[0]);
		String password = PasswordUtil.encrypt(userName, oldpassword, PasswordUtil.getStaticSalt());
		/*String query = "from TSUser u where u.userName = :username and u.password=:passowrd";
		Query queryObject = getSession().createQuery(query);
		queryObject.setParameter("username", user.getUserName());
		queryObject.setParameter("passowrd", password);
		List<TSUser> users = queryObject.list();*/
		Map<String, Object> para=new HashMap();
		String sql=new SQL(){{
			SELECT("bu.*,u.*");
			FROM("T_S_BASE_USER bu");

		    INNER_JOIN("T_S_USER u on bu.ID=u.ID and bu.STATUS='1'");
		    WHERE("(bu.USER_NAME=#{userName} or u.MOBILE_PHONE=#{userName})");
		    WHERE("bu.PASSWORD=#{password}");
	    }}.toString();
		para.put("sql", sql);
		//sql="select bu.*,u.* from T_S_BASE_USER bu inner join T_S_USER u on bu.ID=u.ID and bu.STATUS='1' where (bu.USER_NAME='"+user.getUserName()+"' or u.MOBILE_PHONE='"+user.getUserName()+"') and bu.PASSWORD='"+password+"'";
		para.put("userName", userName);
		para.put("password", password);
		//List<TSUser> users =userMapper.selectListBySql(para);
		List<TSUser> users =sqlMapper.selectList(sql, para,TSUser.class);
		//List<TSUser> users =heroService.findByQueryString(sql, TSUser.class, para);
		if (users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}

	public String getUserRole(TSUser user) {
		String userRole = "";
		Map para=new HashMap();
		para.put("userId", user.getId());
		List<String> roleCodeList=userMapper.getUserRoleList(para);
		//List<TSRoleUser> sRoleUser = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
		for (String roleCode : roleCodeList) {
			userRole += roleCode + ",";
		}
		return userRole;
	}

	public void pwdInit(TSUser user, String newPwd) {
		/*String query ="from TSUser u where u.userName = :username ";
		Query queryObject = getSession().createQuery(query);
		queryObject.setParameter("username", user.getUserName());
		List<TSUser> users =  queryObject.list();*/
		Map para=new HashMap();
		String sql=new SQL(){{
			SELECT("bu.*,u.*");
			FROM("T_S_BASE_USER bu");
		    FROM("");
		    INNER_JOIN("T_S_USER u on bu.ID=u.ID and bu.STATUS='1'");
		    WHERE("bu.USER_NAME=#{username}");
		   // WHERE("bu.PASSWORD=#{password}");
	    }}.toString();
		para.put("sql", sql);
		para.put("username", user.getUserName());
		//para.put("passowrd", password);
		List<TSUser> users =userMapper.selectListBySql(para);
		if(null != users && users.size() > 0){
			user = users.get(0);
			String pwd = PasswordUtil.encrypt(user.getUserName(), newPwd, PasswordUtil.getStaticSalt());
			user.setPassword(pwd);
			commonService.save(user);
		}
	}

	public int getUsersOfThisRole(String id) {
		/*Criteria criteria = getSession().createCriteria(TSRoleUser.class);
		criteria.add(Restrictions.eq("TSRole.id", id));
		int allCounts = ((Long) criteria.setProjection(Projections.rowCount())
				.uniqueResult()).intValue();*/
		String sql="select count(DISTINCT ru.USER_ID) from T_S_ROLE_USER ru where ru.ROLE_ID='"+id+"'";
		Map para=new HashMap();
		para.put("sql", sql);
		int allCounts = commonMapper.selectCountBySql(para).intValue();
		return allCounts;
	}

	public List<ZNodes> getUserMenu(ZNodes znode, String userId) {
		Map paraMap=new HashMap();
		paraMap.put("userId", userId);
		paraMap.put("pid", znode.getPid());
		paraMap.put("plevel", znode.getPlevel());
		return this.userMapper.getZNodes(paraMap);
	}

	public Long selectUserAcount(Map parameter) {
		Long size = Long.valueOf(0L);

		/*Map parameter = new HashMap();
		String mobilePhone = request.getParameter("mobilePhone");
		String officePhone = request.getParameter("officePhone");
		String userName = request.getParameter("userName");
		String realName = request.getParameter("realName");
		parameter.put("userName", userName);
		parameter.put("realName", realName);
		parameter.put("mobilePhone", mobilePhone);
		parameter.put("officePhone", officePhone);*/

		size = userMapper.getUserCount(parameter);

		return size;
	}
	@Override
	public List<TSUser> getUserList(Map parameter) {
		List results = new ArrayList();
		List<TSUser> list = userMapper.getUserList(parameter);
		
		return list;
	}

	public TSUser getTSUser(String id) {
		// TODO Auto-generated method stub
		return userMapper.getTSUser(id);
	}
	
	public String getPartDeptNames(String partids){
		String names="";
		partids=partids.replace(",", "','");
		partids="'"+partids+"'";
		Map para=new HashMap();
		para.put("partids", partids);
		String sql="select d.DEPART_NAME from T_S_DEPART d where d.ID in ("+partids+")";
		List<String> nameList=commonService.getStringListBySql(sql, para);
		for(String name:nameList){
			names=names+name+",";
		}
		return names;
	}
	

	public List<Map> checkUserExits(String username, String pwd) {
	 Map map=new HashMap();
	 map.put("username", username);
	  map.put("password", pwd);
		return userMapper.checkuserAndGetRole(map);
	}
	@Override
	public Long getUserCount(Map dataMap) {
		// TODO Auto-generated method stub
		return userMapper.getUserCount(dataMap);
	}

	@Override
	public List<TSUser> getUserListByRole(Map map) {
		return userMapper.getUserListByRole(map);
	}

	@Override
	public TSUser getUserById(String id) {
		Map<String, String> para=new HashMap();
		String sql=new SQL(){{
			SELECT("bu.*,u.*");
			FROM("T_S_BASE_USER bu");

		    INNER_JOIN("T_S_USER u on bu.ID=u.ID and bu.STATUS='1'");
		    WHERE("bu.ID=#{id} ");
	    }}.toString();
		//para.put("sql", sql);
		para.put("id", id);
		/*List<TSUser> users =userMapper.selectListBySql(para);
		if (users != null && users.size() > 0) {
			return users.get(0);
		}*/
		return sqlMapper.selectOne(sql, para, TSUser.class);
	}
	


/*	@Override
	public AjaxJson importUserForExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		// params.setNeedSave(true);
		List<ImpUser> listuser = actUserMapper.getImpUserList(new HashMap());
		List<TSUser> tuserList = new ArrayList();
		List<TSRoleUser> troleuserList = new ArrayList();
		//List<ActIdMembership> actroleuserList = new ArrayList();
		//List<ActIdUser> actuserList = new ArrayList();
		List<String> userNameList = new ArrayList();
		for (ImpUser impUser : listuser) {
			String userId = impUser.getId();
			String roleid = impUser.getRoleid() == null ? "8afc99b04c26ad0b014c26af28930043"
					: impUser.getRoleid();
			if (StringUtil.isNotEmpty(roleid)) {
				TSUser user = new TSUser();
				String username = PinyinUtil.getPinYin(impUser.getRealName());
				String uuname;
				if (impUser.getEmail() == null
						|| impUser.getEmail().trim().equals("")
						|| impUser.getEmail().indexOf("@") == -1) {
					uuname = username;
				} else
					uuname = impUser.getEmail().split("@")[0];
				if (uuname.trim().equals(""))
					uuname = username;
				if (userNameList.contains(uuname)) {
					uuname = uuname + "1";
				}
				Map uMap = new HashMap();
				uMap.put("USERNAME", uuname);
				Integer ucount = actUserMapper.getBaseUserCount(uMap);
				int ui = 1;
				while (ucount > 0) {
					if (ucount > 0) {
						ui = ui + 1;
						uuname = uuname + ui;
					}
					Map NewMap = new HashMap();
					NewMap.put("USERNAME", uuname);
					ucount = actUserMapper.getBaseUserCount(NewMap);
				}

				if (impUser.getEmail() == null
						|| impUser.getEmail().trim().equals(""))
					impUser.setEmail(uuname + "@gzkit.com.cn");
				userNameList.add(uuname);
				// user.setUserName(username);
				user.setUserName(uuname);
				user.setEmail(impUser.getEmail() == null ? "" : impUser
						.getEmail());
				user.setOfficePhone(impUser.getOfficePhone() == null ? ""
						: impUser.getOfficePhone());
				user.setMobilePhone(impUser.getMobilePhone() == null ? ""
						: impUser.getMobilePhone());
				user.setInterphone(impUser.getInterphone() == null ? ""
						: impUser.getInterphone());
				user.setRealName(impUser.getRealName());
				user.setStatus(Short.valueOf((short) 1));
				user.setActivitiSync(Short.valueOf("1"));
				user.setPassword(PasswordUtil.encrypt(user.getUserName(),
						"123456", PasswordUtil.getStaticSalt()));
				List depts;
				if (impUser.getSubDepartName() != null
						&& !impUser.getSubDepartName().trim().equals(""))
					depts = systemService.findByProperty(TSDepart.class,
							"departname", impUser.getSubDepartName().trim());
				else
					depts = systemService.findByProperty(TSDepart.class,
							"departname", impUser.getDepartName().trim());
				TSDepart dept = (TSDepart) depts.get(0);
				user.setTSDepart(dept);

				Map actUserMemMap = new HashMap();
				actUserMemMap.put("USER_ID_", user.getUserName());
				actUserMemMap.put("GROUP_ID_", "manager");
				Map actUserMap = new HashMap();
				actUserMap.put("ID_", user.getUserName());
				actUserMap.put("REV_", BigDecimal.valueOf(1));
				actUserMap.put("FIRST_", user.getRealName());
				actUserMap.put("LAST_", user.getRealName());
				actUserMap.put("EMAIL_", user.getEmail());
				actUserMap.put("PWD_", user.getPassword());
				int actUserMemCount = actUserMapper
						.getActMemCount(actUserMemMap);
				int actUserCount = actUserMapper.getActUserCount(actUserMap);
				if (actUserCount > 0) {
					actUserMapper.updateActUser(actUserMap);

				} else {
					actUserMapper.insertActUser(actUserMap);
				}
				if (actUserMemCount == 0) {
					actUserMapper.insertUserMem(actUserMemMap);
				}

				// actuserList.add(actUser);

				String userid = UUIDGenerator.generate();
				Map queryBaseUserMap = new HashMap();
				queryBaseUserMap.put("USERNAME", user.getUserName());
				int baseUserCount = actUserMapper
						.getBaseUserCount(queryBaseUserMap);
				if (baseUserCount > 0)
					userid = actUserMapper.getBaseUserId(queryBaseUserMap);
				Map userMap = new HashMap();
				userMap.put("EMAIL",
						user.getEmail() == null ? "" : user.getEmail());
				userMap.put("MOBILEPHONE", user.getMobilePhone() == null ? ""
						: user.getMobilePhone());
				userMap.put("OFFICEPHONE", user.getOfficePhone() == null ? ""
						: user.getOfficePhone());
				userMap.put("LOCATION",
						user.getLocation() == null ? "" : user.getLocation());
				userMap.put("INTERPHONE", user.getInterphone() == null ? ""
						: user.getInterphone());
				userMap.put("ID", userid);

				Map baseUserMap = new HashMap();
				baseUserMap.put("ID", userid);
				baseUserMap.put("ACTIVITISYNC", "1");
				baseUserMap.put("PASSWORD", user.getPassword());
				baseUserMap.put("REALNAME", user.getRealName());
				baseUserMap.put("STATUS", "1");
				baseUserMap.put("USERNAME", user.getUserName());
				baseUserMap.put("DEPARTID", user.getTSDepart().getId());
				if (baseUserCount > 0) {
					actUserMapper.updateBaseUser(baseUserMap);
					actUserMapper.updateUser(userMap);
				} else {
					actUserMapper.insertBaseUser(baseUserMap);
					actUserMapper.insertUser(userMap);
				}

				Map userRoleMap = new HashMap();
				userRoleMap.put("ID", user.getUserName());
				userRoleMap.put("ROLEID", roleid);
				userRoleMap.put("USERID", userid);
				int roleUserCount = actUserMapper.getRoleUserCount(userRoleMap);
				if (roleUserCount > 0) {
					actUserMapper.updateRoleUser(userRoleMap);
				} else {
					actUserMapper.insertRoleUser(userRoleMap);
				}
			}
		}
		String message="";
		if (StringUtil.isNotEmpty(message))
			j.setMsg("SQL文件导入失败," + message);
		else
			j.setMsg("SQL文件导入成功");

		return j;

	}*/



}
